package com.jmlee.controller;

import com.jmlee.component.HostHolder;
import com.jmlee.enums.ItemStatus;
import com.jmlee.enums.RoleEnums;
import com.jmlee.exception.Asserts;
import com.jmlee.pojo.*;
import com.jmlee.service.AItemService;
import com.jmlee.service.ShopService;
import com.jmlee.util.JSONUtil;
import com.jmlee.util.SystemDateUtil;
import com.jmlee.util.UploadUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ItemController {
    @Autowired
    private AItemService aItemService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private HostHolder hostHolder;



    @Value("${default.path.upload}")
    private String uploadPath;


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat upsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 访问商品列表
     *
     * @return
     */
    @GetMapping("itemManager")
    public String itemManager() {
        Admin admin = hostHolder.getAdmin();
        if (admin.getRoleId() == 1L || admin.getRoleId() == 3L) {
            return "AdminItemManager";
        } else {
            return "itemManager";
        }
    }

    /**
     * 拉取商品列表
     *
     * @param curPage
     * @param pageSize
     * @param aItem
     * @return
     */
    @PostMapping("itemList")
    @ResponseBody
    public CommonResult getItemList(String curPage, String pageSize, AItem aItem) {

        Admin admin = hostHolder.getAdmin();

        Long roleId = admin.getRoleId();

        CommonPage commonPage = new CommonPage();
        if (aItem == null) {
            aItem = new AItem();
            if (roleId == RoleEnums.SHOP.getrId()) {
                aItem.setShopId(1L);
            }
        }
        commonPage.setData(aItemService.getItemsList(new RowBounds((Integer.parseInt(curPage) - 1) * Integer.parseInt(pageSize), Integer.parseInt(pageSize)), aItem));
        commonPage.setCount(aItemService.getRecordCount(aItem));
        return CommonResult.success(commonPage, "success");
    }

    /**
     * 新增商品
     *
     * @param itemMap
     * @return
     */
    @PostMapping("createNewItem")
    @ResponseBody
    public String createdNewItem(@RequestBody Map<String, Object> itemMap) {
        Integer state = 0;
        Admin admin = hostHolder.getAdmin();

        Long shopId = Long.valueOf(shopService.queryShopById(admin.getId()).getId());

        String aItem = JSONUtil.objectToJson(itemMap.get("aItem"));
        String aItemParam = JSONUtil.objectToJson(itemMap.get("aItemParam"));

        String aItemMainImage = itemMap.get("mainImage").toString();
        String aItemImgList = itemMap.get("imageList").toString();

        AItem aItemBean = JSONUtil.jsonToPojo(aItem, AItem.class);
        aItemBean.setShopId(shopId);
        aItemBean.setCreatedTime(SystemDateUtil.getDaDate());
        /*
            判断商品是否为优选商品
            0 否 上架
            1 是 进入审核阶段
         */
        if (aItemBean.getIsSpecial() == 0) {
            aItemBean.setOnOffStatus(ItemStatus.ON_LINE.getCode());
        } else {
            aItemBean.setOnOffStatus(ItemStatus.UN_CHECK.getCode());
        }
        AItemParam aItemParamBean = JSONUtil.jsonToPojo(aItemParam, AItemParam.class);
        AItemImg aMainItemImg = JSONUtil.jsonToPojo(aItemMainImage, AItemImg.class);
        List<AItemImg> aItemImageList = JSONUtil.jsonToList('['+aItemImgList+']', AItemImg.class);
        aItemBean.setIcon(aMainItemImg.getUrl());
        state = aItemService.addItemInfo(aItemBean);
        Long itemId = aItemBean.getId();

        if (state == 1) {
            aMainItemImg.setItemId(itemId);
            aMainItemImg.setIsMain(1);
            aMainItemImg.setCreatedTime(SystemDateUtil.getDaDate());
            aMainItemImg.setSort(1);
            state = aItemService.addItemImage(aMainItemImg);
            Integer sort = 1;
            for (AItemImg aItemImg : aItemImageList) {
                sort = 1;
                aItemImg.setItemId(itemId);
                aItemImg.setIsMain(0);
                aItemImg.setCreatedTime(SystemDateUtil.getDaDate());
                aItemImg.setSort(sort);
                sort++;
                state = aItemService.addItemImage(aItemImg);
            }
            state = aItemService.addItemParam(itemId, aItemParamBean);
        }
        return state.toString();
    }

    /**
     * 上传商品图片
     *
     * @param file
     * @return
     */
    @PostMapping("uploadItemImages")
    @ResponseBody
    public CommonResult uploadItemImages(@RequestBody MultipartFile file) {
        AItemImg aItemImg = new AItemImg();

        // 比如：/static/upload/2021/03/12/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径,指定nginx的代理路径
            String filePath = "http://47.99.200.116/" + format + "/" + newName;


            aItemImg.setUrl(filePath);


        } catch (IOException e) {
            return CommonResult.failed("网络异常");
        }

        return CommonResult.success(JSONUtil.objectToJson(aItemImg));
    }


    /**
     * 上传主图
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadMainItemImage")
        @ResponseBody
    public CommonResult upload(@RequestBody MultipartFile file) {

        AItemImg aItemImg = new AItemImg();

        // 比如：/static/upload/2021/03/12/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
        File folder = new File(uploadPath + format);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径,指定nginx的代理路径
            String filePath = "http://47.99.200.116/" + format + "/" + newName;


            aItemImg.setUrl(filePath);


        } catch (IOException e) {
            return CommonResult.failed("网络异常");
        }

        return CommonResult.success(JSONUtil.objectToJson(aItemImg));
    }


    @PostMapping("enableItem")
    @ResponseBody
    public String enableItem(@RequestBody AItem aItem) {
        aItem.setOnOffStatus(1);
        return aItemService.editItemInfo(aItem).toString();
    }

    @PostMapping("disableItem")
    @ResponseBody
    public String disableItem(@RequestBody AItem aItem) {
        aItem.setOnOffStatus(2);
        return aItemService.editItemInfo(aItem).toString();
    }

    @PostMapping("editStock")
    @ResponseBody
    public String editStock(@RequestBody AItem aItem) {
        aItem.setOnOffStatus(1);
        return aItemService.editItemInfo(aItem).toString();
    }


    /**
     * 编辑商品
     *
     * @param itemMap
     * @return
     */
    @PostMapping("editItem")
    @ResponseBody
    public String editItemInfo(@RequestBody Map<String, Object> itemMap) {
        String state = "0";
        String aItem = JSONUtil.objectToJson(itemMap.get("aItem"));
        String aItemParam = JSONUtil.objectToJson(itemMap.get("aItemParam"));
        AItem aItemBean = JSONUtil.jsonToPojo(aItem, AItem.class);
        AItemParam aItemParamBean = JSONUtil.jsonToPojo(aItemParam, AItemParam.class);
        state = aItemService.editItemInfo(aItemBean).toString();
        if (aItemService.getAItemParam(aItemParamBean.getItemId()) == null) {
            state = aItemService.addItemParam(aItemParamBean.getItemId(), aItemParamBean).toString();
        } else {
            state = aItemService.editItemParam(aItemParamBean).toString();
        }
        return state;
    }


    @PostMapping("/uploadLayEditImg")
    @ResponseBody
    public Map<String,Object> layEditImg(@RequestBody MultipartFile file){
        Map<String,Object> imgJson = new LinkedHashMap<>();
        Map<String,Object> imgInfo = new LinkedHashMap<>();
        String format = sdf.format(new Date());
        String title = file.getOriginalFilename();
        File folder = new File(uploadPath + format);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String newName = UUID.randomUUID().toString()
                + title.substring(title.lastIndexOf("."), title.length());
        try {
            // 文件保存
            file.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径,指定nginx的代理路径
            String filePath = "http://47.99.200.116/" + format + "/" + newName;
            imgJson.put("code",0);
            imgInfo.put("src",filePath);
            imgInfo.put("title",title);
            imgJson.put("data",imgInfo);
        } catch (IOException e) {
            imgJson.put("code",500);
            imgJson.put("msg","error");
            return imgJson;
        }
        return imgJson;
    }

}
